/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-25 11:05:11
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.core.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyAppListBean;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.core.bean.*;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseTypeGroup;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.repository.BaseTypeGroupDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.service.BaseTypeGroupItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/base/type-group-item")
@Api(tags = "系统管理-数据字典")
public class BaseTypeGroupItemController {

    private static final Logger logger = LoggerFactory.getLogger(BaseTypeGroupItemController.class);

    @Autowired
    private BaseTypeGroupItemService baseTypeGroupItemService;
    @Autowired
    private BaseTypeGroupDao typeGroupDao;
    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;


    @PostMapping("addItem")
    @ApiOperation(value = "增加字典")
    @RequiresPermissions("base:type-group:addItem")
    public ResultBean addItem(@RequestBody BaseTypeGroupItemBean bean) {
        BaseTypeGroupItem item = baseTypeGroupItemService.addItem(bean);
        return ResultBean.success(item);
    }

    @PostMapping("addListItem")
    @ApiOperation(value = "批量增加数据字典")
    @RequiresPermissions("base:type-group:addListItem")
    public ResultBean addListItem(@RequestBody List<BaseTypeGroupItemBean> list) {
        List<BaseTypeGroupItem> listItem = baseTypeGroupItemService.addListItem(list);
        return ResultBean.success(listItem);
    }

    @PostMapping("updateItem")
    @ApiOperation(value = "修改字典")
    @RequiresPermissions("base:type-group:updateItem")
    public ResultBean updateItem(@RequestBody BaseTypeGroupItemBean bean) {
        BaseTypeGroupItem item = baseTypeGroupItemService.updateItem(bean);
        return ResultBean.success(item);
    }

    @GetMapping("deleteItem")
    @ApiOperation(value = "删除字典")
    @RequiresPermissions("base:type-group:deleteItem")
    public ResultBean deleteItem(Long id) {
        baseTypeGroupItemService.deleteItem(id);
        return ResultBean.success("");
    }

    @GetMapping("findItemById")
    @ApiOperation(value = "查看字典")
    public ResultBean findItemById(Long id) {
        BaseTypeGroupItemBean bean = baseTypeGroupItemService.findItemById(id);
        return ResultBean.success(bean);
    }

    @GetMapping("pageItem")
    @ApiOperation(value = "分页查看字典")
    public ResultBean pageItem(Pageable page, BaseTypeGroupItemSearchBean condition) throws ParseException {
        Page<BaseTypeGroupItemBean> p = baseTypeGroupItemService.pageItem(page, condition);
        return ResultBean.pageData(p.getContent(), p.getTotalElements());
    }

    @RequestMapping("add")
    public Object add(@Valid BaseTypeGroupItem entity) {
        try {
            baseTypeGroupItemService.add(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("创建失败", e);
            return ResultBean.fail(101, "创建失败");
        }
    }

    @RequestMapping("update")
    public Object update(@Valid BaseTypeGroupItem entity) {
        try {
            if (entity.getId() == null) {
                return ResultBean.fail(102, "未指定主键");
            }
            baseTypeGroupItemService.update(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("更新失败：#" + entity.getId(), e);
            return ResultBean.fail(101, "更新失败");
        }
    }

    @RequestMapping("page")
    public Object page(Pageable page) {
        try {
            Page<BaseTypeGroupItem> data = baseTypeGroupItemService.findByPage(page);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("list")
    public Object list(@Valid @NotNull(field = "类型") String type) {
        try {
            BaseTypeGroup typeGroup = typeGroupDao.findByCode(type);
            List<TypeGroupItemBean> list = new ArrayList<TypeGroupItemBean>();
            if (typeGroup != null) {
                Set<BaseTypeGroupItem> items = typeGroup.getBaseTypeGroupItems();
                if (CollectionUtils.isNotEmpty(items)) {
                    for (BaseTypeGroupItem b : items) {
                        TypeGroupItemBean bean = new TypeGroupItemBean();
                        bean.setCode(b.getCode());
                        bean.setId(b.getId());
                        bean.setName(b.getName());

                        if (b.getState() == DataStateTypes.EFFECTIVE.getState()) {
                            list.add(bean);
                        }
                    }
                }
            }
            return ResultBean.success(list);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("list-by-name")
    public Object listByName(@Valid @NotNull(field = "类型") String name) {
        try {
            BaseTypeGroup typeGroup = typeGroupDao.findByName(name);
            Set<BaseTypeGroupItem> items = typeGroup.getBaseTypeGroupItems();
            List<TypeGroupItemBean> list = new ArrayList<TypeGroupItemBean>();
            for (BaseTypeGroupItem b : items) {
                TypeGroupItemBean bean = new TypeGroupItemBean();
                bean.setCode(b.getCode());
                bean.setId(b.getId());
                bean.setName(b.getName());
                list.add(bean);
            }
            return ResultBean.success(list);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("simple-list-by-name")
    public Object simpleListByName(String name) {
        try {
            BaseTypeGroup typeGroup = typeGroupDao.findByName(name);
            if (typeGroup == null) {
                return ResultBean.success(Collections.EMPTY_LIST);
            }
            List<BaseTypeGroupItem> items = baseTypeGroupItemDao.findByTypeGroupId(typeGroup.getId());
            //Set<BaseTypeGroupItem> items = typeGroup.getBaseTypeGroupItems();
            List<SimpleSelectListBean> list = new ArrayList<SimpleSelectListBean>();
            Collections.sort(items, new Comparator<BaseTypeGroupItem>() {

                @Override
                public int compare(BaseTypeGroupItem o1, BaseTypeGroupItem o2) {
                    if (o1.getShowOrder() != null && o2.getShowOrder() != null) {
                        return o1.getShowOrder().compareTo(o2.getShowOrder());
                    } else {
                        return o1.getId().compareTo(o2.getId());
                    }

                }
            });
            for (BaseTypeGroupItem b : items) {
                SimpleSelectListBean bean = new SimpleSelectListBean();
                bean.setValue(b.getId());
                bean.setLabel(b.getName());
                list.add(bean);
            }
            // list.sort(Comparator.comparing(SimpleSelectListBean::getValue));
            return ResultBean.success(list);
        } catch (Exception e) {
            logger.error("查询失败", e);
            return ResultBean.fail(101, "查询失败：" + e.getMessage());
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            baseTypeGroupItemService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }
}
